<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>WebSocket 和 HTTP 消息测试</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            max-width: 800px;
            margin: 0 auto;
            padding: 20px;
        }
        .container {
            display: flex;
            gap: 20px;
        }
        .panel {
            flex: 1;
            border: 1px solid #ccc;
            padding: 15px;
            border-radius: 5px;
        }
        h2 {
            margin-top: 0;
            color: #333;
        }
        button {
            padding: 8px 15px;
            background-color: #4CAF50;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            margin: 5px 0;
        }
        button:hover {
            background-color: #45a049;
        }
        button:disabled {
            background-color: #cccccc;
        }
        textarea, input {
            width: 100%;
            padding: 8px;
            margin: 5px 0 15px 0;
            box-sizing: border-box;
            border: 1px solid #ddd;
            border-radius: 4px;
        }
        #log {
            height: 200px;
            overflow-y: auto;
            border: 1px solid #ddd;
            padding: 10px;
            background-color: #f9f9f9;
            white-space: pre-wrap;
        }
        .status {
            padding: 5px;
            margin: 5px 0;
            border-radius: 3px;
        }
        .connected {
            background-color: #dff0d8;
            color: #3c763d;
        }
        .disconnected {
            background-color: #f2dede;
            color: #a94442;
        }
    </style>
</head>
<body>
<h1>WebSocket 和 HTTP 消息测试</h1>

<div class="container">
    <!-- WebSocket 面板 -->
    <div class="panel">
        <h2>WebSocket 连接</h2>

        <div>
            <label for="wsUserId">用户ID:</label>
            <input type="text" id="wsUserId" value="user456">
            <button id="wsConnectBtn">连接</button>
            <button id="wsDisconnectBtn" disabled>断开</button>
        </div>

        <div id="wsStatus" class="status disconnected">未连接</div>

        <div>
            <label for="wsRecipient">收件人ID:</label>
            <input type="text" id="wsRecipient" value="user123">
        </div>

        <div>
            <label for="wsMessage">消息内容:</label>
            <textarea id="wsMessage" rows="3">你好，这是通过WebSocket发送的消息</textarea>
            <button id="wsSendBtn" disabled>通过WS发送</button>
        </div>

        <h3>WebSocket 日志</h3>
        <div id="wsLog" class="log"></div>
    </div>

    <!-- HTTP 面板 -->
    <div class="panel">
        <h2>HTTP 发送消息</h2>

        <div>
            <label for="httpSender">发送者ID:</label>
            <input type="text" id="httpSender" value="user456">
        </div>

        <div>
            <label for="httpRecipient">收件人ID:</label>
            <input type="text" id="httpRecipient" value="user123">
        </div>

        <div>
            <label for="httpMessage">消息内容:</label>
            <textarea id="httpMessage" rows="3">你好，这是通过HTTP发送的消息</textarea>
            <button id="httpSendBtn">通过HTTP发送</button>
        </div>

        <h3>HTTP 响应</h3>
        <div id="httpLog" class="log"></div>
    </div>
</div>

<script>
    // WebSocket 相关功能
    let ws = null;
    const wsUserIdInput = document.getElementById('wsUserId');
    const wsConnectBtn = document.getElementById('wsConnectBtn');
    const wsDisconnectBtn = document.getElementById('wsDisconnectBtn');
    const wsStatusDiv = document.getElementById('wsStatus');
    const wsRecipientInput = document.getElementById('wsRecipient');
    const wsMessageInput = document.getElementById('wsMessage');
    const wsSendBtn = document.getElementById('wsSendBtn');
    const wsLogDiv = document.getElementById('wsLog');

    // HTTP 相关功能
    const httpSenderInput = document.getElementById('httpSender');
    const httpRecipientInput = document.getElementById('httpRecipient');
    const httpMessageInput = document.getElementById('httpMessage');
    const httpSendBtn = document.getElementById('httpSendBtn');
    const httpLogDiv = document.getElementById('httpLog');

    // WebSocket 连接
    wsConnectBtn.addEventListener('click', () => {
        const userId = wsUserIdInput.value.trim();
        if (!userId) {
            logToWs('用户ID不能为空');
            return;
        }

        ws = new WebSocket(`ws://127.0.0.1:8079/api/v1/ai/ws/${userId}`);

        ws.onopen = () => {
            wsStatusDiv.textContent = '已连接';
            wsStatusDiv.className = 'status connected';
            wsConnectBtn.disabled = true;
            wsDisconnectBtn.disabled = false;
            wsSendBtn.disabled = false;
            logToWs(`WebSocket 连接已建立 (用户: ${userId})`);
        };

        ws.onmessage = (event) => {
            logToWs(`收到消息: ${event.data}`);
        };

        ws.onerror = (error) => {
            logToWs(`WebSocket 错误: ${error.message}`);
        };

        ws.onclose = () => {
            wsStatusDiv.textContent = '未连接';
            wsStatusDiv.className = 'status disconnected';
            wsConnectBtn.disabled = false;
            wsDisconnectBtn.disabled = true;
            wsSendBtn.disabled = true;
            logToWs('WebSocket 连接已关闭');
        };
    });

    // WebSocket 断开连接
    wsDisconnectBtn.addEventListener('click', () => {
        if (ws) {
            ws.close();
        }
    });

    // 通过 WebSocket 发送消息
    wsSendBtn.addEventListener('click', () => {
        if (!ws || ws.readyState !== WebSocket.OPEN) {
            logToWs('WebSocket 未连接');
            return;
        }

        const recipient = wsRecipientInput.value.trim();
        const message = wsMessageInput.value.trim();

        if (!recipient || !message) {
            logToWs('收件人和消息内容不能为空');
            return;
        }

        const msg = {
            type: "message",
            recipient: recipient,
            content: message
        };

        ws.send(JSON.stringify(msg));
        logToWs(`已发送消息给 ${recipient}: ${message}`);
    });

    // 通过 HTTP 发送消息
    httpSendBtn.addEventListener('click', async () => {
        const sender = httpSenderInput.value.trim();
        const recipient = httpRecipientInput.value.trim();
        const message = httpMessageInput.value.trim();

        if (!sender || !recipient || !message) {
            logToHttp('发送者、收件人和消息内容不能为空');
            return;
        }

        try {
            const response = await fetch('http://127.0.0.1:8079/api/v1/ai/ws/send', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    sender: sender,
                    recipient: recipient,
                    content: message
                })
            });

            const result = await response.json();
            logToHttp(`HTTP 响应: ${JSON.stringify(result, null, 2)}`);
        } catch (error) {
            logToHttp(`HTTP 请求错误: ${error.message}`);
        }
    });

    // 日志函数
    function logToWs(message) {
        const timestamp = new Date().toLocaleTimeString();
        wsLogDiv.innerHTML += `[${timestamp}] ${message}\n`;
        wsLogDiv.scrollTop = wsLogDiv.scrollHeight;
    }

    function logToHttp(message) {
        const timestamp = new Date().toLocaleTimeString();
        httpLogDiv.innerHTML += `[${timestamp}] ${message}\n`;
        httpLogDiv.scrollTop = httpLogDiv.scrollHeight;
    }
</script>
</body>
</html>